import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;
import javafx.scene.input.KeyCode;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
import javafx.util.Duration;

public class StoryScene {
    private static final String[] STORY_IMAGES = {
            "/images/story1.png",
            "/images/story2.png",
            "/images/story3.png"
    };

    private static final String[] STORY_TEXTS = {
            "第七个满月升起时，黑森林被月光照着。古老的试炼契约在月光中舒展，将森林与城堡连缀成符文甬道。",
            "为了继承前任魔女的位置，我们的主角——小魔女伊雷娜，需从森林一直跑到城堡。",
            "据说从来没有魔女到达过城堡的深处。这一次的修行，不仅是为了锻炼自己，也是为了证明自己的能力，足以继承魔女的位置。"
    };

    private static final String TEXT_BOX_IMAGE = "/images/textBox.png";
    private static final String CONTINUE_TEXT = "(鼠标单击或空格继续)";

    private int currentStoryIndex = 0;
    private Stage primaryStage;
    private Main mainApp;
    private StringBuilder displayedText = new StringBuilder();
    private Timeline textAnimation;
    private Image textBoxImage;

    public StoryScene(Stage primaryStage, Main mainApp) {
        this.primaryStage = primaryStage;
        this.mainApp = mainApp;
        try {
            this.textBoxImage = new Image(getClass().getResourceAsStream(TEXT_BOX_IMAGE));
        } catch (Exception e) {
            this.textBoxImage = null; // 如果图片加载失败，回退到纯色背景
        }
    }

    public Scene createStoryScene() {
        StackPane root = new StackPane();
        Canvas canvas = new Canvas(GameConstants.getScreenWidth(), GameConstants.getScreenHeight());
        root.getChildren().add(canvas);

        Scene scene = new Scene(root);
        showStory(canvas.getGraphicsContext2D());

        // 设置键盘和鼠标事件
        scene.setOnKeyPressed(e -> {
            if (e.getCode() == KeyCode.SPACE) {
                proceedToNextStory(canvas.getGraphicsContext2D());
            }
        });

        scene.setOnMouseClicked(e -> {
            if (e.getButton() == MouseButton.PRIMARY) {
                proceedToNextStory(canvas.getGraphicsContext2D());
            }
        });

        return scene;
    }

    private void showStory(GraphicsContext gc) {
        gc.clearRect(0, 0, GameConstants.getScreenWidth(), GameConstants.getScreenHeight());
        if (currentStoryIndex >= STORY_IMAGES.length) {
            // 所有故事显示完毕，开始游戏
            mainApp.isNewGame = false;
            mainApp.startNewGame();
            return;
        }

        // 清除画布
        gc.clearRect(0, 0, GameConstants.getScreenWidth(), GameConstants.getScreenHeight());

        // 加载并绘制故事背景图片
        Image storyImage = new Image(getClass().getResourceAsStream(STORY_IMAGES[currentStoryIndex]));
        gc.drawImage(storyImage, 0, 0, GameConstants.getScreenWidth(), GameConstants.getScreenHeight());

        // 重置显示的文本
        displayedText.setLength(0);

        // 创建文本动画
        if (textAnimation != null) {
            textAnimation.stop();
        }

        textAnimation = new Timeline(
                new KeyFrame(Duration.millis(60), e -> {
                    if (displayedText.length() < STORY_TEXTS[currentStoryIndex].length()) {
                        displayedText.append(STORY_TEXTS[currentStoryIndex].charAt(displayedText.length()));
                        drawText(gc);
                    }
                })
        );
        textAnimation.setCycleCount(STORY_TEXTS[currentStoryIndex].length());
        textAnimation.play();
    }

    private void drawText(GraphicsContext gc) {
        // 1. 清除并重新绘制整个场景
        gc.clearRect(0, 0, GameConstants.getScreenWidth(), GameConstants.getScreenHeight());

        // 重新绘制背景图
        Image storyImage = new Image(getClass().getResourceAsStream(STORY_IMAGES[currentStoryIndex]));
        gc.drawImage(storyImage, 0, 0, GameConstants.getScreenWidth(), GameConstants.getScreenHeight());

        // 2. 计算文本区域参数
        double textAreaHeight = GameConstants.getScreenHeight() * 0.25;
        double textAreaY = GameConstants.getScreenHeight() - textAreaHeight;
        double cornerRadius = 15;

        // 3. 绘制半透明背景层
        gc.setGlobalAlpha(0.6);
        gc.setFill(Color.rgb(50, 50, 50));
        gc.fillRoundRect(
                0, textAreaY,
                GameConstants.getScreenWidth(), textAreaHeight,
                cornerRadius, cornerRadius
        );
        gc.setGlobalAlpha(1.0);

        // 4. 绘制文本框
        if (textBoxImage != null) {
            gc.drawImage(
                    textBoxImage,
                    0, textAreaY,
                    GameConstants.getScreenWidth(), textAreaHeight
            );
        }

        // 5. 文本参数计算
        double fontSize = Math.max(18, GameConstants.getScreenHeight() * 0.028);
        gc.setFont(Font.font("Microsoft YaHei", FontWeight.BOLD, fontSize));
        gc.setFill(Color.WHITE);

        // 6. 安全处理文本换行
        String text = displayedText.toString();
        double textX = GameConstants.getScreenWidth() * 0.08;
        double textY = textAreaY + textAreaHeight * 0.35;
        double maxWidth = GameConstants.getScreenWidth() * 0.85;
        double lineHeight = fontSize * 1.4;
        double padding = 10;

        // 中文换行逻辑
        int charIndex = 0;
        while (charIndex < text.length()) {
            // 安全检查：确保至少有一个字符
            if (charIndex >= text.length()) break;

            // 计算当前行能容纳的字符数
            int charsThisLine = 1;
            while (charIndex + charsThisLine <= text.length()) {
                String testLine = text.substring(charIndex, charIndex + charsThisLine);
                double textWidth = com.sun.javafx.tk.Toolkit.getToolkit()
                        .getFontLoader().computeStringWidth(testLine, gc.getFont());

                if (textWidth > maxWidth) {
                    // 如果超宽且不是第一个字符，则回退一个字符
                    if (charsThisLine > 1) charsThisLine--;
                    break;
                }

                // 安全边界检查
                if (charIndex + charsThisLine >= text.length()) {
                    break;
                }
                charsThisLine++;
            }

            // 安全截取子字符串
            int endIndex = Math.min(charIndex + charsThisLine, text.length());
            String line = text.substring(charIndex, endIndex);
            gc.fillText(line, textX, textY);

            // 更新位置
            charIndex += charsThisLine;
            textY += lineHeight;

            // 检查是否超出文本框
            if (textY > textAreaY + textAreaHeight - padding) {
                break;
            }
        }

        // 7. 绘制固定提示文本（右下角）
        double hintFontSize = fontSize;
        gc.setFont(Font.font("Microsoft YaHei", FontWeight.BOLD, hintFontSize));
        gc.setFill(Color.rgb(200, 200, 200));

        String hintText = CONTINUE_TEXT;
        double hintTextWidth = com.sun.javafx.tk.Toolkit.getToolkit()
                .getFontLoader().computeStringWidth(hintText, gc.getFont());

        gc.fillText(
                hintText,
                GameConstants.getScreenWidth() - hintTextWidth - 50,
                GameConstants.getScreenHeight() - 50
        );
    }

    private void proceedToNextStory(GraphicsContext gc) {
        if (textAnimation != null && textAnimation.getStatus() == Animation.Status.RUNNING) {
            // 如果动画还在进行，直接显示全部文本
            textAnimation.stop();
            displayedText = new StringBuilder(STORY_TEXTS[currentStoryIndex]);
            drawText(gc);
        } else {
            // 否则进入下一个故事
            currentStoryIndex++;
            showStory(gc);
        }
    }
}